/**
 * @projectName: petJoyHome
 * @author: 小飞
 * @description: TODO
 * @date: 2024/3/2 20:10
 * @version: 1.0
 */
package com.home.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.home.constant.MessageConstant;
import com.home.entity.LoginUser;
import com.home.entity.RoleMenu;
import com.home.entity.User;
import com.home.entity.UserRole;
import com.home.exception.BaseException;
import com.home.exception.LoginFailedException;
import com.home.mapper.RoleMenuMapper;
import com.home.mapper.UserMapper;
import com.home.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(user)) {
            throw new LoginFailedException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //TODO 查询对应打的权限信息
        List<String> list = userMapper.selectPermsByUserId(user.getId());
        List<UserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        List<RoleMenu> roleMenus = roleMenuMapper.selectBatchIds(userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
        user.setRoleTypes(roleMenus.stream().map(RoleMenu::getId).map(Long::intValue).collect(Collectors.toList()));
        list.addAll(roleMenus.stream().map(RoleMenu::getRoleName).collect(Collectors.toList()));
        return new LoginUser(user,list);
    }
}
